<?php

namespace App\Http\Controllers\Admin;

use App\Exports\QhCdkeyExport;
use App\Exports\QhNetCourseCdkeyExport;
use App\Http\Requests\Admin\Qh_CdkeyGroupRequest;
use App\Http\Requests\Admin\Qh_NetCourseCdkeyGroupRequest;
use App\Models\NetCourseCdkey;
use App\Models\NetCourseCdkeyGroup;
use Carbon\Carbon;
use Exception;
use Illuminate\Http\JsonResponse;
use Maatwebsite\Excel\Facades\Excel;

class Qh_NetCourseCdkeyGroupController extends AdminBaseController
{
    /**
     * Display a listing of the resource.
     *
     * @return JsonResponse|object
     */
    public function index()
    {
        $list = NetCourseCdkeyGroup::filter(\request()->all())
            ->with([
                'learnVideo' => function($q) {
                    $q->select(['id', 'name']);
                },
                'courseColumn' => function($q) {
                    $q->select(['id', 'name']);
                }
            ])
            ->orderByDesc('id')
            ->paginate(\request('perPage', 10));
        return $this->restful($list);
    }

    /**
     * 生成激活码
     * Store a newly created resource in storage.
     *
     * @param Qh_NetCourseCdkeyGroupRequest $request
     * @return JsonResponse|object
     * @throws Exception
     * @throws \Throwable
     */
    public function store(Qh_NetCourseCdkeyGroupRequest $request)
    {
        $params = $request->validated();

        if ($params['count'] > 1000) {
            throw new Exception('每次最多生成1000个');
        }

        try {
            \DB::beginTransaction();
            if (!empty($params['expires'])) $params['expires'] = Carbon::createFromTimestamp($params['expires'], 'Asia/Shanghai');
            $cdkeyGroup = NetCourseCdkeyGroup::create($params);
            // 生成激活码
            for ($i=0; $i<$params['count'];$i++) {
                NetCourseCdkey::create([
                    'groupId' => $cdkeyGroup->id,
                    'code' => generateCdkey(),
                    'expires' => $params['expires'],
                    'type' => $params['type'],
                    'dataId' => !empty($params['dataId']) ? $params['dataId'] : null,
                    'effective_type' => !empty($params['effective_type']) ? $params['effective_type'] : null,
                    'effective_days' => !empty($params['effective_days']) ? $params['effective_days'] : null,
                    'effective_hours' => !empty($params['effective_hours']) ? $params['effective_hours'] : null,
                    'effective_date' => !empty($params['effective_date']) ? $params['effective_date'] : null,
                ]);
            }

            \DB::commit();
        }catch (Exception $e) {
            \DB::rollBack();
            throw new Exception('生成失败');
        }

        return $this->restful();
    }

    /**
     * 增加激活码数量
     * Update the specified resource in storage.
     *
     * @param Qh_NetCourseCdkeyGroupRequest $request
     * @param int $id
     * @return JsonResponse|object
     * @throws \Throwable
     */
    public function update(Qh_NetCourseCdkeyGroupRequest $request, int $id)
    {
        $params = $request->validated();
        if (!empty($params['expires'])) $params['expires'] = Carbon::createFromTimestamp($params['expires'], 'Asia/Shanghai');
        $cdkeyGroup = NetCourseCdkeyGroup::findOrFail($id);

        if ($params['count'] > 1000) {
            throw new Exception('每次最多生成1000个');
        }

        try {
            \DB::beginTransaction();
            $cdkeyGroup->count = $cdkeyGroup->count + $params['count'];
            $cdkeyGroup->save();

            // 生成激活码
            for ($i=0; $i<$params['count'];$i++) {
                NetCourseCdkey::create([
                    'groupId' => $cdkeyGroup->id,
                    'code' => generateCdkey(),
                    'expires' => $params['expires'],
                    'type' => $params['type'],
                    'dataId' => $cdkeyGroup->dataId,
                    'effective_type' => !empty($params['effective_type']) ? $params['effective_type'] : null,
                    'effective_days' => !empty($params['effective_days']) ? $params['effective_days'] : null,
                    'effective_hours' => !empty($params['effective_hours']) ? $params['effective_hours'] : null,
                    'effective_date' => !empty($params['effective_date']) ? $params['effective_date'] : null,
                ]);
            }

            \DB::commit();
        }catch (Exception $e) {
            \DB::rollBack();
            throw new Exception('生成失败');
        }

        return $this->restful();
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param int $id
     * @return JsonResponse|object
     * @throws \Throwable
     */
    public function destroy(int $id)
    {
        try {
            \DB::beginTransaction();
            $result = NetCourseCdkeyGroup::where('id', $id)->delete();

            // 删除对应的激活码
            $cdkeyList = NetCourseCdkey::where('groupId', $id)->get();
            foreach ($cdkeyList as $cdkey) {
                $cdkey->delete();
            }

            \DB::commit();
        }catch (Exception $e) {
            \DB::rollBack();
            throw new Exception('删除失败');
        }

        return $this->restful($result);
    }

    /**
     * @throws Exception
     */
    public function export($id)
    {
        $ids = NetCourseCdkey::where('groupId', $id)->pluck('id')->toArray();

        if (count($ids) < 1)  throw new Exception('缺少参数');
        $filename = '激活码'.time().'.xlsx';

        try {
            $result = Excel::store(new QhNetCourseCdkeyExport(['ids' => $ids]), $filename, 'public');
            if (!$result) throw new Exception('导出失败');
        }catch (Exception $e) {
            throw new Exception('导出失败');
        }

        return $this->restful([
            'filename' => $filename,
            'url' => \Storage::disk('public')->url($filename)
        ]);
    }
}
